#include <iostream>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string>
#include <unistd.h>
#include "log.hpp"

#define BUFFERSIZE 1024
using std::string;
extern Log lg;

enum client_errno
{
    SUCCESS = 0,
    CONNECT_FAILED,
    SOCKETFD_FAILED,
};

void manual(const char *argv)
{
    printf("%s ip port\n", argv);
}

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        manual(argv[0]);
        exit(1);
    }

    sockaddr_in server;
    uint16_t server_port = std::stoi(argv[2]);
    server.sin_family = AF_INET;
    inet_pton(AF_INET, argv[1], &server.sin_addr);
    server.sin_port = htons(server_port);

    // bool reconnect = false;
    // int rc_time = 5;
    // do
    // {
    //     int ret = connect(socketfd, (sockaddr *)&server, sizeof(server));
    //     if (ret == -1)
    //     {
    //         rc_time--;
    //         reconnect = true;
    //         lg(WARNING, "connetion failed,reconnecting! %d:%s", errno, strerror(errno));
    //     }
    //     else
    //     {
    //         break;
    //     }
    // } while (rc_time > 0 && reconnect);

    // if (rc_time <= 0)
    // {
    //     lg(FATAL, "connection error");
    //     exit(1);
    // }
    // lg(INFO, "connection sucess");

    // 重复connet同一个fd会阻塞
    while (true)
    {
        int socketfd = 0;
        bool isreconnet = false;
        int cnt = 5;
        do
        {
            socketfd = socket(AF_INET, SOCK_STREAM, 0);
            if (socketfd == -1)
            {
                lg(FATAL, "socketfd create failed %d:%s", errno, strerror(errno));
                exit(SOCKETFD_FAILED);
            }
            // lg(INFO, "socketfd create success %d:%s", errno, strerror(errno));
            int ret = connect(socketfd, (sockaddr *)&server, sizeof(server));
            if (ret == -1)
            {
                isreconnet = true;
                std::cerr << "connect error..., reconnect: " << cnt << std::endl;
                sleep(2);
                cnt--;
            }
            else
            {
                isreconnet = false;
            }
        } while (isreconnet && cnt);

        if(cnt <= 0)
        {
            std::cerr<< "reconnect failed!"<<std::endl;
            exit(CONNECT_FAILED);
        }

        // while(true) 长服务 
        // {
        std::cout << "input:";
        string message;
        getline(std::cin, message);
        int ret = write(socketfd, message.c_str(), message.size());
        if(ret == -1)
        {
            std::cerr<<"client write failed!"<<std::endl;
        }

        char inbuffer[BUFFERSIZE];
        int n = read(socketfd, inbuffer, sizeof(inbuffer));
        if(n == -1)
        {
            std::cerr<<"client write failed!"<<std::endl;
        }
        inbuffer[n] = 0;
        std::cout << inbuffer << std::endl;
        close(socketfd);
    
    }

    return 0;
}